package br.unicamp.mc715;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import junit.framework.TestCase;
import br.unicamp.mc715.transport.UDPTransportId;


public class HermanVerjusTest extends TestCase {
	
	
	
	public void test1() throws IOException, InterruptedException {
		int numServers = 5;
		int numClients = 5;
		int numAccounts = 10;
		File[] logs = new File[numServers];
		Process[] servers = new Process[numServers];
		Process[] clients = new Process[numClients];
		UDPTransportId[] ids = new UDPTransportId[numServers];
		
		//Inicia "numServers" instancias do servidor
		for (int i=0; i<numServers; i++) {
			logs[i] = new File("server_"+i+".log"); //File.createTempFile("HermanVerjus_"+i+"_", ".log");
			servers[i] = Runtime.getRuntime().exec(
					new String[] {
						"/usr/bin/java",
						"-cp",
						"lib/log4j.jar:build",
						"br.unicamp.mc715.bank.BankServer",
						Integer.toString(numAccounts),
						logs[i].getCanonicalPath(),
						Integer.toString(numServers)
					});
		}
		//Lê o endereço em que cada servidor iniciou
		for (int i=0; i<numServers; i++) {
			String line = new BufferedReader(new InputStreamReader(servers[i].getInputStream())).readLine();
			String id = line.replaceAll("^.*Middleware rodando em ", "");
			System.out.println("Server #"+i+" rodando em "+id);
			
			ids[i] = new UDPTransportId(id);
		}
		
		//Inicia "numClients" AutoClients
		for (int i=0; i<numClients; i++) {
			int j = (int)(Math.random()*numServers);
			
			clients[i] = Runtime.getRuntime().exec(
					new String[] {
						"/usr/bin/java",
						"-cp",
						"lib/log4j.jar:build",
						"br.unicamp.mc715.bank.BankClient",
						"auto",
						Integer.toString(numAccounts),
						ids[j].toString()
					});
		}
		
		//Processa, processa, processa....
		
		//Espera os clientes terminarem
		for (Process p : clients) {
			p.waitFor();
		}
		
		//Espera os servidores terminarem. 
		//Neste caso, como não tem uma mensagem de shutdown, a gente dá um tempinho e manda um kill ;)
		Thread.sleep(10000);
		for (Process p : servers) {
			p.destroy();
			p.waitFor();
		}
	}
}
